package pet_pavilion.yushouge.ams.service.impl;

import cn.tedu.yushouge.commons.ex.ServiceException;
import cn.tedu.yushouge.commons.pojo.po.AdminLoginInfoPO;
import cn.tedu.yushouge.commons.pojo.vo.PageData;
import cn.tedu.yushouge.commons.web.ServiceCode;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import pet_pavilion.yushouge.ams.mapper.AdminMapper;
import pet_pavilion.yushouge.ams.mapper.AdminRoleMapper;
import pet_pavilion.yushouge.ams.pojo.dto.AdminLoginInfoDTO;
import pet_pavilion.yushouge.ams.pojo.entity.Admin;
import pet_pavilion.yushouge.ams.pojo.entity.AdminRole;
import pet_pavilion.yushouge.ams.pojo.param.AdminAddNewParam;
import pet_pavilion.yushouge.ams.pojo.param.AdminLoginInfoParam;
import pet_pavilion.yushouge.ams.pojo.param.AdminUpdateInfoParam;
import pet_pavilion.yushouge.ams.pojo.vo.AdminListVO;
import pet_pavilion.yushouge.ams.pojo.vo.AdminStandardVO;
import pet_pavilion.yushouge.ams.repository.IAdminJwtRepository;
import pet_pavilion.yushouge.ams.security.AdminDetails;
import pet_pavilion.yushouge.ams.service.AdminService;
import pet_pavilion.yushouge.ams.util.PageInfoToPageDataConverter;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private AdminRoleMapper adminRoleMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private IAdminJwtRepository adminCacheRepository;

    @Value("${yushouge.jwt.duration-in-minute}")
    private Long durationInMinute;

    @Value("${yushouge.jwt.secret-key}")
    private String secretKey;

    public AdminServiceImpl() {
        log.debug("创建业务类对象：AdminServiceImpl");
    }

    @Override
    public AdminLoginInfoDTO login(AdminLoginInfoParam adminLoginInfoParam,
                                   String remoteAddr, String userAgent) {
        log.debug("开始处理【管理员登录】的业务，参数：{}", adminLoginInfoParam);
        Authentication authentication = new UsernamePasswordAuthenticationToken(
                adminLoginInfoParam.getUsername(),
                adminLoginInfoParam.getPassword());
        authenticationManager.authenticate(authentication);
        Authentication authenticationResult = authenticationManager.authenticate(authentication);
        log.debug("验证登录完成，认证结果：{}", authenticationResult);

        AdminDetails adminDetails = (AdminDetails) authenticationResult.getPrincipal();

        Map<String, Object> claims = new HashMap<>();
        claims.put("id", adminDetails.getId());
        claims.put("username", adminDetails.getUsername());
        String authorityListJsonString = JSON.toJSONString(adminDetails.getAuthorities());

        long tokenDuration = durationInMinute * 60 * 1000;
        Date tokenExpiration = new Date(System.currentTimeMillis() + tokenDuration);
        String jwt = Jwts.builder()
                // Header
                .setHeaderParam("alg", "HS256")
                .setHeaderParam("typ", "JWT")
                // Payload
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis() + durationInMinute * 1000 * 60))
                // Verify Signature
                .signWith(SignatureAlgorithm.HS256, secretKey)
                // 生成
                .compact();
        log.debug("生成了此管理员的信息对应的JWT：{}", jwt);

        AdminLoginInfoPO adminLoginInfoPO = new AdminLoginInfoPO();
        adminLoginInfoPO.setId(adminDetails.getId());
        adminLoginInfoPO.setEnable(adminDetails.isEnabled() ? 1 : 0);
        adminLoginInfoPO.setRemoteAddr(remoteAddr);
        adminLoginInfoPO.setUserAgent(userAgent);
        adminLoginInfoPO.setAuthorityListJsonString(authorityListJsonString);
        adminCacheRepository.saveLoginInfo(jwt, adminLoginInfoPO, tokenDuration);
        log.debug("向Redis中写入此管理员的登录信息：{}", adminLoginInfoPO);

        AdminLoginInfoDTO adminLoginInfoDTO = new AdminLoginInfoDTO()
                .setId(adminDetails.getId())
                .setUsername(adminDetails.getUsername())
                .setAvatar(adminDetails.getAvatar())
                .setToken(jwt)
                .setTokenExpiration(tokenExpiration);

        return adminLoginInfoDTO;
    }

    @Override
    public void logout(String jwt) {
        log.debug("开始处理【管理员退出登录】的请求，参数：{}", jwt);
        adminCacheRepository.delete(jwt);
    }


    @Override
    public void addNew(AdminAddNewParam adminAddNewParam) {
        log.debug("开始处理【添加管理员】的业务，参数：{}", adminAddNewParam);
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", adminAddNewParam.getUsername());
        int countByName = adminMapper.selectCount(queryWrapper);
        log.debug("根据管理员名称统计匹配的管理员数量，结果：{}", countByName);
        if (countByName > 0) {
            String message = "添加管理员失败，管理员名称已经被占用!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        QueryWrapper<Admin> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("phone", adminAddNewParam.getPhone());
        int countByPhone = adminMapper.selectCount(queryWrapper2);
        log.debug("根据管理员手机号码统计匹配的管理员数量，结果：{}", countByPhone);
        if (countByPhone > 0) {
            String message = "添加管理员失败，管理员手机号码已经被占用!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        QueryWrapper<Admin> queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("email", adminAddNewParam.getEmail());
        int countByEmail = adminMapper.selectCount(queryWrapper3);
        log.debug("根据管理员电子邮箱统计匹配的管理员数量，结果：{}", countByEmail);
        if (countByEmail > 0) {
            String message = "添加管理员失败，管理员电子邮箱已经被占用!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        Admin admin = new Admin();
        BeanUtils.copyProperties(adminAddNewParam, admin);
        admin.setPassword(passwordEncoder.encode(admin.getPassword()));
        admin.setLastLoginIp(null);
        admin.setLoginCount(0);
        admin.setGmtLastLogin(null);
        admin.setGmtCreate(LocalDateTime.now());
        admin.setGmtModified(LocalDateTime.now());
        int rows = adminMapper.insert(admin);
        if (rows != 1) {
            String message = "添加管理员失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }

        // 将管理员与角色的关联数据写入到数据库中
        Long[] roleIds = adminAddNewParam.getRoleIds();
        AdminRole[] adminRoleList = new AdminRole[roleIds.length];
        LocalDateTime now = LocalDateTime.now();
        for (int i = 0; i < adminRoleList.length; i++) {
            AdminRole adminRole = new AdminRole();
            adminRole.setAdminId(admin.getId());
            adminRole.setRoleId(roleIds[i]);
            adminRole.setGmtCreate(now);
            adminRole.setGmtModified(now);
            adminRoleList[i] = adminRole;
        }
        rows = adminRoleMapper.insertBatch(adminRoleList);
        if (rows != adminRoleList.length) {
            String message = "添加管理员失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
        log.debug("将新的管理员与角色的关联数据插入到数据库，完成！");
    }

    @Override
    public void delete(Long id) {
        log.debug("开始处理【删除管理员】的业务，参数：{}", id);
        int rows = adminMapper.deleteByAdminId(id);
        log.debug("从数据库删除一条数据，完成！");
    }

    @Override
    public void setEnable(Long id) {
        log.debug("开始处理【启用管理員】的业务，参数：{}", id);
        updateEnableById(id, 1);
    }

    @Override
    public void setDisable(Long id) {
        log.debug("开始处理【禁用管理員】的业务，参数：{}", id);
        updateEnableById(id, 0);
    }

    private void updateEnableById(Long id, Integer enable) {
        AdminStandardVO currentAdmin = adminMapper.getStandardById(id);

        if (currentAdmin == null) {
            String message = ENABLE_TEXT[enable] + "管理員失败，管理員数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        if (currentAdmin.getEnable() == enable) {
            String message = ENABLE_TEXT[enable] + "管理員失败，此管理員已经处于" + ENABLE_TEXT[enable] + "状态！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        Admin updateAdmin = new Admin();
        updateAdmin.setId(id);
        updateAdmin.setEnable(enable);

        int rows = adminMapper.updateById(updateAdmin);
        if (rows != 1) {
            String message = ENABLE_TEXT[enable] + "管理員失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
    }

    @Override
    public void updateById(Long id, AdminUpdateInfoParam adminUpdateInfoParam) {
        log.debug("开始处理【修改管理员信息详情】的业务，ID：{}，新数据：{}", id, adminUpdateInfoParam);
        // 检查相册是否存在，如果不存在，则抛出异常
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        int countById = adminMapper.selectCount(queryWrapper);
        log.debug("根据管理员ID统计匹配的管理员数量，结果：{}", countById);
        if (countById == 0) {
            String message = "修改管理员密码失败，管理员不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        QueryWrapper<Admin> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("phone", adminUpdateInfoParam.getPhone())
                .ne("id", id);
        int countByPhone = adminMapper.selectCount(queryWrapper2);
        log.debug("根据管理员手机号码统计匹配的管理员数量，结果：{}", countByPhone);
        if (countByPhone > 0) {
            String message = "修改管理员信息详情失败，管理员手机号码已经被占用！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        QueryWrapper<Admin> queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("email", adminUpdateInfoParam.getEmail())
                .ne("id", id);
        int countByEmail = adminMapper.selectCount(queryWrapper3);
        log.debug("根据管理员邮箱统计匹配的管理员数量，结果：{}", countByEmail);
        if (countByEmail > 0) {
            String message = "修改管理员信息详情失败，管理员邮箱已经被占用！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        Admin admin = new Admin();
        admin.setId(id);
        String newPassword = adminUpdateInfoParam.getPassword();
        admin.setPassword(passwordEncoder.encode(newPassword));
        BeanUtils.copyProperties(adminUpdateInfoParam, admin);
        int rows = adminMapper.updateById(admin);
        if (rows != 1) {
            String message = "修改管理员信息失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
        log.debug("将新的管理员信息更新入到数据库，完成！");
    }

    @Override
    public AdminStandardVO getStandardById(Long id) {
        log.debug("开始处理【根据ID查询管理员详情】的业务，参数：{}", id);
        AdminStandardVO queryResult = adminMapper.getStandardById(id);
        if (queryResult == null) {
            String message = "查询管理员详情失败，管理员数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        return queryResult;
    }


    @Override
    public PageData<AdminListVO> list(Integer page, Integer pageSize) {
        log.debug("开始处理【查询管理员列表】的业务，页码：{}，每页记录数：{}", page, pageSize);
        PageHelper.startPage(page, pageSize);
        List<AdminListVO> list = adminMapper.list();
        PageInfo<AdminListVO> pageInfo = new PageInfo<>(list);
        PageData<AdminListVO> pageData = PageInfoToPageDataConverter.convert(pageInfo);
        log.debug("查询完成，即将返回：{}", pageData);
        return pageData;
    }

    @Override
    public PageData<AdminListVO> list(Integer page) {
        Integer pageSize = 5;
        return list(page, pageSize);
    }

}
